package com.sjyl.kaoshitong.witget;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.sjyl.kaoshitong.beans.CatalogItem;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by ChangerLow on 15/7/1.
 * Email: changerlow@qq.com
 */
public class FilterBranchSelectorTreeDialog extends DialogFragment implements MaterialDialog.ListCallback {
    private static String TAG = "FilterBranchSelectorTreeDialog";
    private File parentFolder;
    private File[] parentContents;
    private boolean canGoUp = true;
    private FolderSelectCallback mCallback;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Hawk.init(getActivity());
        List<CatalogItem> list = Hawk.get("catalog_list");
        int maxLevel = Hawk.get("filter_max_level", 0);
        Logger.d(TAG, "sdasdasfadfasfsafsafdasdf " + list.get(0).getCatalog_name());
       /* for (int j = 0 ; j <= maxLevel; j++){
            List<String> levelList = catalogLevelMap.get(j);
            Logger.d(TAG, "=========print Level " + j + "  list size " + levelList.size());
            for( int k  = 0; k < levelList.size(); k++){
                String key = levelList.get(k);
                Logger.d(TAG, "=====level "+ j +"  key " + key + "   pid "+catalogItemMap.get(key).getPid());
            }
        }*/
    }

    private final MaterialDialog.ButtonCallback mButtonCallback = new MaterialDialog.ButtonCallback() {
        @Override
        public void onPositive(MaterialDialog materialDialog) {
            materialDialog.dismiss();
            mCallback.onFolderSelection(parentFolder);
        }

        @Override
        public void onNegative(MaterialDialog materialDialog) {
            materialDialog.dismiss();
        }
    };

    public interface FolderSelectCallback {
        void onFolderSelection(File folder);
    }


    public static FilterBranchSelectorTreeDialog newInstance(String arg){
        FilterBranchSelectorTreeDialog dialog = new FilterBranchSelectorTreeDialog();
        Bundle bundle = new Bundle();
        dialog.setArguments(bundle);
        return dialog;
    }

    public FilterBranchSelectorTreeDialog() {
        parentFolder = Environment.getExternalStorageDirectory();
        parentContents = listFiles();
    }

    String[] getContentsArray() {
        String[] results = new String[parentContents.length + (canGoUp ? 1 : 0)];
        if (canGoUp) results[0] = "...";
        for (int i = 0; i < parentContents.length; i++)
            results[canGoUp ? i + 1 : i] = parentContents[i].getName();
        return results;
    }

    File[] listFiles() {
        File[] contents = parentFolder.listFiles();
        List<File> results = new ArrayList<>();
        for (File fi : contents) {
            if (fi.isDirectory()) results.add(fi);
        }
        Collections.sort(results, new FolderSorter());
        return results.toArray(new File[results.size()]);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new MaterialDialog.Builder(getActivity())
                .title(parentFolder.getAbsolutePath())
                .items(getContentsArray())
                .itemsCallback(this)
                .callback(mButtonCallback)
                .autoDismiss(false)
                .positiveText("Choose")
                .negativeText(android.R.string.cancel)
                .build();
    }

    @Override
    public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence s) {
        if (canGoUp && i == 0) {
            parentFolder = parentFolder.getParentFile();
            canGoUp = parentFolder.getParent() != null;
        } else {
            parentFolder = parentContents[canGoUp ? i - 1 : i];
            canGoUp = true;
        }
        parentContents = listFiles();
        MaterialDialog dialog = (MaterialDialog) getDialog();
        dialog.setTitle(parentFolder.getAbsolutePath());
        if (getContentsArray().length > 1) {
            Logger.d(TAG, "===========has child items");
            dialog.setItems(getContentsArray());
        }else{
            Logger.d(TAG, "===========has no child items");
            if (view instanceof TextView) {
                dialog.setSelectedIndex(dialog.getSelectedIndex());
            }
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mCallback = (FolderSelectCallback)getTargetFragment();
    }



    private static class FolderSorter implements Comparator<File> {
        @Override
        public int compare(File lhs, File rhs) {
            return lhs.getName().compareTo(rhs.getName());
        }
    }
}
